/*
 * Copyright (c) 2020-2099 the original author or authors. All rights reserve.
 */
package org.tianyun.cloud.mybatis.autoconfigure;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.boot.autoconfigure.MybatisProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.tianyun.cloud.datasource.autoconfigure.DataSourceAutoConfiguration;
import org.tianyun.cloud.mybatis.plugins.MybatisPagePlugin;
import org.tianyun.cloud.mybatis.plugins.RequestContextPlugin;

import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.List;

/**
 * MybatisAutoConfiguration
 *
 * @auther ebert_chan
 */
@Configuration(proxyBeanMethods = false)
@Import(DataSourceAutoConfiguration.class)
public class MybatisAutoConfiguration {

    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource, MybatisProperties mybatiesProperties) throws Exception {
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();

        SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
        factory.setDataSource(dataSource);
        factory.setPlugins(new MybatisPagePlugin(), new RequestContextPlugin());

        Resource resource = resolver.getResource("classpath:mybatis-config.xml");
        if (resource != null) {
            factory.setConfigLocation(resource);
        }

        String[] mapperLocations = mybatiesProperties.getMapperLocations();
        if (mapperLocations == null || mapperLocations.length == 0) {
            mapperLocations = new String[]{"classpath*:mapper/**/*.xml"};
        }

        List<Resource> resourceList = new ArrayList<>();
        for (int i = 0; i < mapperLocations.length; i++) {
            Resource[] resources = resolver.getResources(mapperLocations[i]);
            if (resources != null && resources.length > 0) {
                for (int j = 0; j < resources.length; j++) {
                    resourceList.add(resources[j]);
                }
            }
        }

        if (resourceList != null && !resourceList.isEmpty()) {
            factory.setMapperLocations(resourceList.stream().toArray(Resource[]::new));
        }

        return factory.getObject();
    }

}
